Page({
  data: {
    motorcycleList: [],
    visible: false
  },

  onLoad() {
    const motorcycleList = wx.getStorageSync('motorcycleList') || []
    this.setData({
      motorcycleList: [...motorcycleList].sort((a, b) => b.order - a.order)
    })
  },

  handleMotorcycleItemClick(e) {
    const { motorcycleName, otr } = e.currentTarget.dataset.motorcycle
    wx.navigateTo({
      url: `../../HaveOTRPage/index/index?motorcycleName=${motorcycleName}&otr=${otr}`
    })
  },

  handleHaveOTRBtnClick() {
    wx.navigateTo({
      url: '../../HaveOTRPage/index/index?motorcycleName=&otr=',
    });
  },

  handleDeleteBtnClick(e) {
    const motorcycleToDelete = e.currentTarget.dataset.motorcycle;
    wx.showModal({
      title: '确认删除',
      content: `确定要删除 ${motorcycleToDelete.motorcycleName} 吗？`,
      success: (res) => {
        if (res.confirm) {
          this.deleteMotorcycle(motorcycleToDelete);
        }
      },
    });
  },

  deleteMotorcycle(motorcycleToDelete) {
    let motorcycleList = wx.getStorageSync('motorcycleList') || [];
    motorcycleList = motorcycleList.filter(
      (item) => item.motorcycleName !== motorcycleToDelete.motorcycleName
    );
    wx.setStorageSync('motorcycleList', motorcycleList);
    this.setData({
      motorcycleList: [...motorcycleList].sort((a, b) => b.order - a.order),
    });
  },
});
